package net.oschina.dajiangnan.wx.process.pay.tools;

import net.oschina.dajiangnan.util.XStreamHelper;
import net.oschina.dajiangnan.wx.util.HttpTookit;
import net.oschina.dajiangnan.wx.util.RandomUtil;
import net.oschina.dajiangnan.wx.util.Signature;
import org.apache.log4j.Logger;

import net.oschina.dajiangnan.wx.constants.Config;
import net.oschina.dajiangnan.wx.process.pay.bean.CloseOrderResult;
import net.oschina.dajiangnan.wx.process.pay.xmlbean.CloseOrderReq;
import net.oschina.dajiangnan.wx.process.pay.xmlbean.CloseOrderResp;

public class Orderclose {

	// 关闭订单
	private static final String CLOSE_ORDER_URL = "https://api.mch.weixin.qq.com/pay/closeorder";

	private static Logger logger = Logger.getLogger(Orderclose.class);

	/**
	 * 关闭订单
	 * 
	 * @param out_trade_no
	 *            商户内部订单号
	 * @return BaseResult
	 */
	public static CloseOrderResult closeOrder(String out_trade_no) {
		logger.info("Colse order,out_trade_no:" + out_trade_no);
		CloseOrderReq req = new CloseOrderReq();
		req.setOut_trade_no(out_trade_no);
		req.setAppid(Config.appid);
		req.setMch_id(Config.mch_id);
		req.setNonce_str(RandomUtil.getRandomStr(32));
		try {
			req.setSign(Signature.getSign(req, null, Config.apikey));
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		logger.debug("CloseOrder Request XML:\r\n" + req.toString());
		String xml_resp_str = new HttpTookit().doPost(CLOSE_ORDER_URL,req.toString(),null,null,"UTF-8");
		logger.debug("CloseOrder Response XML:\r\n" + xml_resp_str);
		CloseOrderResp resp = XStreamHelper.toBean(xml_resp_str,CloseOrderResp.class);

		CloseOrderResult result = new CloseOrderResult();
		if (resp.getReturn_code().equals("SUCCESS")) {
			result.setReturn_code(resp.getReturn_code());
			result.setReturn_msg(resp.getReturn_msg());
			result.setResult_code(resp.getResult_code());
			result.setAppid(resp.getAppid());
			result.setMch_id(resp.getMch_id());
			result.setNonce_str(resp.getNonce_str());
			result.setSign(resp.getSign());
			result.setErr_code(resp.getErr_code());
			result.setErr_code_des(resp.getErr_code_des());
		} else {
			result.setReturn_code(resp.getReturn_code());
			result.setReturn_msg(resp.getReturn_msg());
		}
		logger.info("Colse order result" + result.toString());
		return result;
	}
}
